package soap.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import soap.dao.ImageDtoRepository;
import soap.manager.ImgInfoManager;
import soap.pojo.ImageDto;
import soap.service.ImageDtoService;

import java.io.IOException;
import java.util.*;

/**
 * Created by ZhangPY on 2021/9/7
 * Belong Organization OVERUN-9299
 * overun9299@163.com
 * Explain: TestUtils
 */
@Component
public class TestUtils {

    @Autowired
    private ImageDtoRepository imageDtoRepository;

    @Autowired
    private ImgInfoManager imgInfoManager;

    @Autowired
    private ImageDtoService imageDtoService;


    private static String pt_key = "AAJhi8nXADBfWbp6r-Rt5QnQfkbh6vSThEpRoJlvnR-yWotmOVV-qxES_2KjenPxKj7nX20PqQ4;";
    private static String pt_pin = "jd_5a8a2c43bcbdd;";
    private static String pt_token = "gvpajtmq;";
    private static String totalCookie = "__jdu=16365518989941865074633; cud=50c6e560f0bf5d1ece864232af5035fc; TrackID=1ROJLu03ezZHOLWefQvfpTSAUJgAgEw85O9LE65gKgQzunEAV0yU0woLZ4SBDGNu39VbWNvsuEZ9vNVzBxHAX0mmNvQjygpGANV-qUG0c92s; pinId=w4fGksFiVLrw4MjwZJbIlLV9-x-f3wj7; pin=jd_5a8a2c43bcbdd; unick=jd_185029laq; _tp=5VfzE05zWbmPnMDOBIpgiTXEwMX%2B5hKwcwGaFRglA1Q%3D; _pst=jd_5a8a2c43bcbdd; shshshfpb=nmRt6Ua6sXFec48uN46smkQ%3D%3D; shshshfpa=93ddeb0f-ebb0-ec82-4567-63b72841e07f-1611411216; ipLoc-djd=27-2376-50235-0; areaId=27; unpl=V2_ZzNtbUFTEBB0AEUBLxpUDWJWQg8SBRBGIlpAXXNMCFZmUEBYclRCFnUURlRnGVgUZAMZWURcQxVFCEdkeBBVAWMDE1VGZxBFLV0CFSNGF1wjU00zQwBBQHcJFF0uSgwDYgcaDhFTQEJ2XBVQL0oMDDdRFAhyZ0AVRQhHZHseXgJjBxJUSl5LHXAIT1N%2fGFoAYAEQbXJQcyVFC09Ucx9ZNWYzE20AAx8TcQFGVXxUXAJlBBZZQl5LHH0AQ1RyHlgEYQYVX0BnQiV2; __jdv=76161171|baidu-pinzhuan|t_288551095_baidupinzhuan|cpc|0f3d30c8dba7459bb52f2eb5eba8ac7d_0_25b4092de2994dacacbbfc789deb0bc4|1636984632630; PCSYCityID=CN_610000_610100_610104; shshshfp=a2ffd1854d5f941ff7d47cc9cf723748; __jda=122270672.16365518989941865074633.1636551899.1637062571.1637247130.4; __jdc=122270672; cvt=4; csn=1; ip_cityCode=2376; 3AB9D23F7A4B3C9B=76JW3AM57UHOTD4HGJPTFFGCCRIRA5AQFCHC4TJ2GBPODMJEWCRYOPJTJECMOAX7X3JVPHIL3ZFN4HFMJZIAS3RLVI; token=25c4516da9998c4ca0acbc23ea84a376,2,909581; __tk=mbmvZnKxmaKljlrPlBbdYCZIolVOjlq4mbmdZbZxnlbOYnJ4mczkVmVPokZkYRlAmJKdiKi4,2,909581; shshshsID=8b84a9d5d1d7d7290a1a385ea17f7395_2_1637247158071; __jdb=122270672.2.16365518989941865074633|4.1637247130";


    public static Map getCookieMap() {
        Map<String, String> cookieMap = new HashMap<>();

        if (cookieMap.size() != 0) {
            return cookieMap;
        }
        String[] split = totalCookie.split(";");
        for (String s : split) {
            String[] split1 = s.split("=");
            cookieMap.put(split1[0] , split1[1]);
        }

        return cookieMap;
    }

    public static void main(String[] args) throws IOException, InterruptedException {

        TestUtils testUtils = new TestUtils();
        testUtils.getJDImg("黄金" , 0);


//        testUtils.tst("//item.jd.com/100022763856.html");



    }


    /**
     * 解析 商品详情
     * @param url
     * @return
     * @throws IOException
     */
    public Set<ImageDto> tst(String url , String searchKey) throws IOException {

        Set<ImageDto> objects = new HashSet<>();
        url = "https:"+url;

        System.out.println(url);

        Map<String, String> cookieMap = new HashMap<>();
        cookieMap.put("pt_key" , pt_key);
        cookieMap.put("pt_pin" , pt_pin);

        /** 2.解析网页 返回的Document就是一个js网页**/
        Document parse = Jsoup.connect(url).ignoreContentType(true).userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12").cookies(getCookieMap()).timeout(600000).get();

        Element bigImg = parse.getElementById("spec-img");
        Element bigImgList = parse.getElementById("spec-list");

        if (bigImgList != null) {
            Elements li = bigImgList.getElementsByTag("li");

            for (Element element : li) {
                ImageDto imageDto = new ImageDto();
                /** 图片url **/
                String src = element.getElementsByTag("img").attr("src");
                String imgUrl = src.replace("s54x54_", "").replace("/n5/", "/n0/");
                /** 图片描述 **/
                String imgDescribe = element.getElementsByTag("img").attr("alt");
                /** 图片的key **/
                String[] split = imgUrl.split("/");
                String keyOne = split[split.length-1];
                String keyTwo = split[split.length-2];
                String imgKey = keyTwo + "_" + keyOne;
                imageDto.setImgUrl(imgUrl).setImgSearchKey(searchKey).setImgDescribe(imgDescribe).setImgKey(imgKey.replace(".jpg","").replace(".png",""));
                objects.add(imageDto);
                System.out.println(imgUrl);
            }
        }



        return objects;
    }

    public Set<ImageDto> getJDImg(String keyword , int page) throws IOException, InterruptedException {

        String url = "";

        if (page == 0) {
            /** 1.获取请求  https://search.jd.com/Search?keyword=java **/
            url = "https://search.jd.com/Search?keyword="+ keyword;
        } else {
            /** 1.获取请求  https://search.jd.com/Search?keyword=java **/
            url = "https://search.jd.com/Search?keyword="+ keyword + "&page=" + page;
        }

        Map<String, String> cookieMap = new HashMap<>();
        cookieMap.put("pt_key" , pt_key);
        cookieMap.put("pt_pin" , pt_pin);


        /** 2.解析网页 返回的Document就是一个js网页**/
        Document parse = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36")
                .cookies(getCookieMap())
                .timeout(600000).get();

        /** 获取商品区域 **/
        Element j_goodsList = parse.getElementById("J_goodsList");

        /** 获取商品li **/
        Elements li = j_goodsList.getElementsByTag("li");

        List<String> goodsDetails = new ArrayList<>();
        for (Element element : li) {
            String attr = element.getElementsByTag("a").get(0).attr("href");
            if (attr.contains("item.jd.com")) {
                goodsDetails.add(attr);
            }
        }


        Set<ImageDto> imgSet = new HashSet<>();
        for (String goodsDetail : goodsDetails) {
            Set<ImageDto> tst = tst(goodsDetail , keyword);
            imgSet.addAll(tst);
        }
        System.out.println(imgSet.size());

        /**
         * 保存至mongodb
         */
//        for (ImageDto imageDto : imgSet) {
//            imageDtoRepository.save(imageDto);
//        }

        if (imgSet.size() > 0) {
            imageDtoService.saveOrUpdateBatch(imgSet);
        }


        return imgSet;


    }
}
